package com.atguigu.chapter11;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/12 9:30
 */
public class Flink21_UDF {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.parseLong(line[1]), Integer.parseInt(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );


        // TODO - UDF
        // 1.创建 表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // 2.将 流 转换成 Table
        tableEnv.createTemporaryView("sensor", sensorDS, $("id"), $("ts"), $("vc"), $("et").rowtime());
        Table sensor = tableEnv.from("sensor");

        // TODO 1.不注册，直接使用
//        sensor
//                .select(call(MyLenth.class, $("id")).as("lenth"))
//                .execute()
//                .print();

        // TODO 2.先注册，再通过 函数名调用（推荐）
        tableEnv.createTemporarySystemFunction("mylenth", MyLenth.class);

        // TableAPI的方式
//        sensor
//                .select($("id"),call("mylenth",$("id")).as("lenth"))
//                .execute()
//                .print();

        // SQL的方式
        tableEnv
                .sqlQuery("select id,mylenth(id) from sensor")
                .execute()
                .print();

        env.execute();
    }

    public static class MyLenth extends ScalarFunction {

        public int eval(String value) {
            return value.length();
        }
    }
}

/**
 */
